package com.sl.permission.activity

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.ActivityCompat
import com.sl.permission.listener.PermissionRequestCallBack
import com.sl.permission.util.PermissionUtil

/**
 * author： suliang
 * 2022/9/28 15:10
 * describe : 申请权限的Activity，一个通明的Activity
 */
class ApplyPermissionActivity : AppCompatActivity() {


    companion object {

        private var callBack: PermissionRequestCallBack? = null

        @JvmStatic
        fun launch(
            context: Context,
            permissions: Array<out String>,
            requestCode: Int,
            permissionCallback: PermissionRequestCallBack
        ) {
            callBack = permissionCallback

            val bundle = Bundle().apply {
                putStringArray("permission", permissions)
                putInt("requestCode", requestCode)
            }
            val intent = Intent(context, ApplyPermissionActivity::class.java).apply {
                putExtras(bundle)
                setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or (Intent.FLAG_ACTIVITY_CLEAR_TOP))
            }
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        intent?.let {
            //获取权限和请求code
            val permissions = it.getStringArrayExtra("permission")
            val requestCode = it.getIntExtra("requestCode", 0)
            if (permissions == null || permissions.isEmpty() || requestCode == 0) {
                finish()
                return
            }
            //检查权限
            if (PermissionUtil.hasPermissionRequest(this, permissions)) {        //通过
                callBack?.permissionSuccess()
                finish()
                return
            }
            //未通过 开始申请
            ActivityCompat.requestPermissions(this, permissions, requestCode)

        } ?: finish()
    }

    /**
     * 权限申请的回调
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //检查是否都成功
        if (PermissionUtil.requestPermissionSuccess(grantResults)){
            callBack?.permissionSuccess()
            finish()
            return
        }
        //是否永久拒绝了权限
        if (PermissionUtil.shouldShowRequestPermissionRationale(this,permissions)){
            callBack?.permissionDeniedForever()
            finish()
            return
        }
        //用户点击了拒绝，但不是永久拒绝
        callBack?.permissionDenied()
        finish()
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0,0)
    }
}